package rsj.service;

import com.rlyy.aibase.utils.base.MapNode;
import com.rlyy.aibase.utils.base.Node;
import com.rlyy.aibase.utils.base.TableNode;
import common.exec.RsjIllegalArgueException;
import common.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import rsj.dao.BilDao;
import rsj.sql.bill.BillDao;
import rsj.sql.user.UserDao;
import rsj.util.BilQuery;
import rsj.util.PaginationData;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import java.util.Objects;

@Component
public class BilService {

    @Autowired
    private BillDao billDao;

    @Autowired
    private UserDao userDao;

    private static final BilDao bilDao = BilDao.getInstance();


    public PaginationData<TableNode> getBilList(BilQuery bilQuery) {
        return bilDao.getBilList(bilQuery);
    }

    public String confirm(MapNode data, String userId) {
        String bilId = data.getValue("Bill_Id");
        Assert.isNotBlank(bilId, "Bill_Id 不能为空！");
        this.checkBill(bilId, userId);
        return bilDao.updateConfirmStatus(bilId);
    }

    public int insertBilCurMonth(String orgId, Map<String, Object> mapNode) throws Exception {
        return bilDao.insertBilCurMonth(orgId, mapNode);
    }

    public void updateCure(Connection conn) throws SQLException {
        bilDao.updateCure(conn);
    }

    /**
     * 判断Bill_Id是不是当前用户的
     *
     * @param billId 账单id
     */
    private void checkBill(String billId, String userId) {
        // 查询此账单所属机构
        Node orgByBillId = billDao.queryBillOrgByBillId(billId);
        String orgId = orgByBillId.value();
        String userOrgId = userDao.queryOrgIdByUser(userId).getValue("User_Org_Id");
        if (!Objects.equals(userOrgId, orgId)) {
            throw new RsjIllegalArgueException("非本人账单、无权限操作");
        }
    }
}
